import json
import requests
from typing import List


class WeChat:
    """微信发送"""

    TO_ALL = '@all'
    AUTH_URL = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={secret_key}'  # 官网认证地址
    SEND_URL = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}'  # 官方发送地址

    def __init__(self, **kwargs):
        self.agent_id = ''  # 发送账号
        self.corp_id = ''  # 企业ID
        self.secret_key = ''  # 密钥
        self.to_user: List[str] = []  # 接收人
        self.to_party: List[str] = []  # 接收群
        if kwargs:
            self.init(**kwargs)

    def init(self, agent_id, corp_id, secret_key, to_user, to_party):
        self.agent_id = agent_id
        self.corp_id = corp_id
        self.secret_key = secret_key
        self.to_user = to_user
        self.to_party = to_party

    def send(self, title='', message='', url=''):
        if not (self.to_user or self.to_party):  # @所有人
            self.to_user = self.TO_ALL

        # 微信消息体
        message = dict(
            to_user=self.to_user,
            toparty=self.to_party,
            msgtype='textcard',
            agentid=self.agent_id,
            textcard=dict(title=title, description=message, url=url, btntxt='详情'),
            safe=0
        )

        resp = requests.get(self.AUTH_URL.format(corp_id=self.corp_id, secret_key=self.secret_key), verify=False)
        if resp.status_code != 200:
            raise Exception('微信Token获取失败')

        token = resp.json().get('access_token')
        if not token:
            raise Exception('微信Token提取失败')

        resp = requests.post(self.SEND_URL.format(token=token), data=json.dumps(message).encode('utf-8'),
                             headers={'Content-Type': 'application/json'}, verify=False)

        if resp.status_code != 200:
            raise Exception('微信消息发送失败')

        if resp.json().get('errcode') != 0:
            raise Exception('微信消息发送失败')


wechat = WeChat()


if __name__ == '__main__':
    wechat.init('1', '2', '3', [], [])
    wechat.send('a', 'bb')
